package com.boot2.core.service;

import com.boot2.core.dao.i.SchedulerTaskDao;
import com.boot2.core.model.SchedulerTask;
import com.boot2.core.scheduler.ScheduleManager;
import com.boot2.core.utils.CronExpressionUtil;
import com.boot2.core.utils.EnvironmentUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author zhangweilin
 * @ClassName: SchedulerTaskService
 * @Description: 【定时任务】 Service
 * @date 2018-6-4 20:23:52
 */
@Service
@CommonsLog
@ConditionalOnProperty(value = "schedule.enable", havingValue = "true")
public class SchedulerTaskManager {

    @Autowired
    SchedulerTaskDao schedulerTaskDao;

    @Autowired
    ScheduleManager scheduleManager;

    @Autowired(required = false)
    SchedulerFactoryBean schedulerFactoryBean;

    @PostConstruct
    public void init() {
        if (null == schedulerFactoryBean) {
            log.info("未开启schedule.enable，不加载调度任务");
            return;
        }
        reScheduleTask();
    }

    /**
     * 重启时，从库中加载全部任务重新进入调度状态
     */
    private void reScheduleTask() {
        //todo 在起初的数量不大的情况下，直接加载全部
        String appName = EnvironmentUtil.getRequiredProperty("spring.application.name");
        Assert.hasText(appName,"spring.application.name 未定义");
        List<SchedulerTask> schedulerTaskList = schedulerTaskDao.findByIsEnabledIsTrueAndAppName(appName);
        if (CollectionUtils.isEmpty(schedulerTaskList)) {
            return;
        }
        int[] count = new int[]{0,0};
        schedulerTaskList.forEach(e -> {
            //扫描到已经不会再被执行的，置为无效，下次重启时将不会被查询到
            if (!CronExpressionUtil.isCanDoExpression(e.getCronExpression())) {
                e.setIsEnabled(false);
                schedulerTaskDao.saveAndFlush(e);
                count[0]++;
                log.info("任务【"+e.getId()+"】将不再被调用，系统已将其关闭");
            }else{
                scheduleManager.scheduleTask(e, true);
                count[1]++;
            }
        });
        log.info("共【" + count[0] + "】条定时任务被废弃...");
        log.info("共【" + count[1] + "】条定时任务重新被调度...");
    }
}
